import os
import numpy as np
import pandas as pd

os.chdir('saliency')

def calculate_averaged_saliency(TYPE,DEVISION,PREDICTOR):
  PREDICTOR=''.join(['%',PREDICTOR,'%'])
  folders=[element for element in os.listdir('.') if TYPE in element and DEVISION in element and PREDICTOR in element]
  print("\n".join(folders))
  saliency_tp=[]
  saliency_tn=[]
  for folder in folders:
    tp=0
    tn=0
    for file in os.listdir(folder):
         if 'tp' in file:
            temp_saliency=np.load('/'.join([folder,file]))
            saliency_tp.append(temp_saliency)
            if temp_saliency.shape != (4,1500) and temp_saliency.shape != (4,3000) :
                 print("check data")
            tp+=1
         if 'tn' in file:
            temp_saliency=np.load('/'.join([folder,file]))
            saliency_tn.append(temp_saliency)
            if temp_saliency.shape != (4,1500) and temp_saliency.shape != (4,3000) :
                 print("check data")
            tn+=1
    print(" ".join([folder,"true positives:",str(tp),"true negatives:",str(tn)]))
  saliency_tp=np.array(saliency_tp)
  saliency_tn=np.array(saliency_tn)
  averaged_saliency_tp=pd.DataFrame(np.average(saliency_tp,axis=0))
  averaged_saliency_tn=pd.DataFrame(np.average(saliency_tn,axis=0))
  averaged_saliency_tp.to_csv("%".join([TYPE,DEVISION,PREDICTOR,'tp']))
  averaged_saliency_tn.to_csv("%".join([TYPE,DEVISION,PREDICTOR,'tn']))

calculate_averaged_saliency('un_vs_expr','subsample_assignment1','Pro_and_Ter')
calculate_averaged_saliency('un_vs_expr','subsample_assignment2','Pro_and_Ter')
calculate_averaged_saliency('un_vs_expr','subsample_assignment3','Pro_and_Ter')
calculate_averaged_saliency('un_vs_expr','subsample_assignment4','Pro_and_Ter')
